#define _CRT_SECURE_NO_WARNINGS 1
#include "List.h"

ListNode* ListCreate(LTDataType n)
{
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (newnode==NULL)
	{
		printf("malloc error\n");
		exit(-1);
	}
	newnode->_data = n;
	newnode->_next = NULL;
	newnode->_prev = NULL;
	return newnode;
}

ListNode* ListInit()
{
	ListNode*pHead = ListCreate(0);
	pHead->_next = pHead->_prev = pHead;
	return pHead;
}

void ListDestory(ListNode* pHead)
{
	assert(pHead);
	ListNode* tmp = pHead;
	while (tmp != pHead)
	{
		ListNode* next = tmp->_next;
		free(tmp);
		tmp = next;
	}
	free(pHead);
	pHead = NULL;
}

void ListPrint(ListNode* pHead)
{
	ListNode* tmp = pHead->_next;
	while (tmp!= pHead)
	{
		ListNode* next = tmp->_next;
		printf("%d ", tmp->_data);
		tmp = next;
	}
	printf("\n");
}

void ListPushBack(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	ListNode* new = ListCreate(x);
	new->_prev = pHead->_prev;
	pHead->_prev->_next = new;
	new->_next = pHead;
	pHead->_prev=new;
}

void ListPushFront(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	ListNode* new = ListCreate(x);
	new->_next = pHead->_next;
	pHead->_next->_prev = new;
	pHead->_next = new;
	new->_prev = pHead;
}

void ListPopBack(ListNode* pHead)
{
	assert(pHead);
	assert(pHead->_next != pHead);

	ListNode* tail = pHead->_prev;
	pHead->_prev = tail->_prev;
	tail->_prev->_next = pHead;
	free(tail);
}

void ListPopFront(ListNode* pHead)
{
	assert(pHead);
	assert(pHead->_next != pHead);

	ListNode* next = pHead->_next;
	pHead->_next = next->_next;
	next->_next->_prev = pHead;
	free(next);
}

ListNode* ListFind(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	ListNode* tmp = pHead->_next;
	while (tmp != pHead)
	{
		if (tmp->_data == x)
		{
			return tmp;
		}
		tmp = tmp->_next;
	}
	return -1;
}

void ListInsert(ListNode* pos, LTDataType x)
{
	assert(pos);
	ListNode* new = ListCreate(x);
	ListPushBack(pos, x);

}

void ListErase(ListNode* pos)
{
	assert(pos);
	//ListNode* prev = pos->_prev;
	//prev->_next = pos->_next;
	//pos->_next->_prev = prev;
	//free(pos);
	ListPopBack(pos);
}